<script setup lang="ts">
import { ref } from 'vue'
import { ElButton, ElInput, ElUpload, ElMessage } from 'element-plus'
import { Upload, Document, Link } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'

const emit = defineEmits<{
  'json-input': [data: any]
}>()

// JSON输入文本
const jsonInput = ref('')

// 文件上传URL
const fileUrl = ref('')

// 处理JSON文本输入
const handleJsonTextInput = () => {
  if (!jsonInput.value.trim()) {
    ElMessage.warning('请输入JSON数据')
    return
  }
  
  try {
    const parsedData = JSON.parse(jsonInput.value)
    emit('json-input', parsedData)
  } catch (error) {
    ElMessage.error('JSON格式错误，请检查输入')
    console.error('JSON解析错误:', error)
  }
}

// 处理文件上传
const handleFileUpload = (file: UploadFile) => {
  if (!file) return false
  
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const content = e.target?.result as string
      const parsedData = JSON.parse(content)
      jsonInput.value = JSON.stringify(parsedData, null, 2)
      emit('json-input', parsedData)
      ElMessage.success('文件上传成功')
    } catch (error) {
      ElMessage.error('文件解析失败，请确保上传的是有效的JSON文件')
      console.error('文件解析错误:', error)
    }
  }
  reader.readAsText(file.raw as Blob)
  return false
}

// 从URL加载JSON
const loadFromUrl = async () => {
  if (!fileUrl.value) {
    ElMessage.warning('请输入URL')
    return
  }
  
  try {
    const response = await fetch(fileUrl.value)
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status}`)
    }
    
    const data = await response.json()
    jsonInput.value = JSON.stringify(data, null, 2)
    emit('json-input', data)
    ElMessage.success('从URL加载成功')
  } catch (error) {
    ElMessage.error('从URL加载失败，请检查URL或网络连接')
    console.error('URL加载错误:', error)
  }
}

// 清空输入
const clearInput = () => {
  jsonInput.value = ''
  fileUrl.value = ''
}

// 生成示例数据
const generateExample = () => {
  const example = {
    name: 'JSON Streaming',
    version: '1.0.0',
    features: ['JSON解析', '实时流处理', '可视化展示'],
    config: {
      autoSave: true,
      theme: 'dark',
      maxDepth: 10
    },
    examples: [
      { id: 1, type: 'simple', value: 'value1' },
      { id: 2, type: 'complex', value: { nested: true } }
    ]
  }
  
  jsonInput.value = JSON.stringify(example, null, 2)
  emit('json-input', example)
}
</script>

<template>
  <div class="json-input">
    <div class="input-header">
      <h3>JSON 输入</h3>
      <div class="input-tools">
        <el-button @click="clearInput">清空</el-button>
        <el-button type="primary" @click="generateExample">生成示例</el-button>
      </div>
    </div>
    
    <div class="input-methods">
      <div class="method">
        <h4><Document /> 直接输入</h4>
        <el-input
          v-model="jsonInput"
          type="textarea"
          :rows="8"
          placeholder="在此输入JSON数据..."
        />
        <el-button type="primary" @click="handleJsonTextInput">解析</el-button>
      </div>
      
      <div class="method">
        <h4><Upload /> 文件上传</h4>
        <el-upload
          class="upload-area"
          action=""
          :auto-upload="false"
          :on-change="handleFileUpload"
          :show-file-list="false"
          accept=".json"
        >
          <el-button type="primary">选择文件</el-button>
          <div class="upload-tip">支持 .json 文件</div>
        </el-upload>
      </div>
      
      <div class="method">
        <h4><Link /> 从URL加载</h4>
        <div class="url-input">
          <el-input
            v-model="fileUrl"
            placeholder="输入JSON文件URL"
          />
          <el-button type="primary" @click="loadFromUrl">加载</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.json-input {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.input-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.input-header h3 {
  margin: 0;
  color: #e5eaf3;
}

.input-tools {
  display: flex;
  gap: 8px;
}

.input-methods {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: auto;
}

.method {
  background-color: #2a2a2a;
  border-radius: 4px;
  padding: 16px;
}

.method h4 {
  margin-top: 0;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #e5eaf3;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #606266;
  border-radius: 4px;
  padding: 20px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.url-input {
  display: flex;
  gap: 8px;
}
</style>